from socket import *
import sys
from threading import Thread

HOST = '0.0.0.0'
PORT = 8888
ADDR = (HOST, PORT)


def request_handle(c):
    print('客户端：', c.getpeername())
    while True:
        data = c.recv(1024)
        # 客户端关掉进程会收到空信息
        if not data:
            break
        print(data.decode())
        c.send(b'OK')
    c.close()


if __name__ == "__main__":
    sockfd = socket(AF_INET, SOCK_STREAM)
    sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sockfd.bind(ADDR)
    sockfd.listen(50)
    while True:
        try:
            c, addr = sockfd.accept()
        except KeyboardInterrupt:
            sys.exit('服务器退出')
        except Exception as e:
            print(e)
            continue
        thread = Thread(target=request_handle, args=(c,))
        # 分支线程随主线程退出
        thread.setDaemon(True)
        thread.start()
